#!/bin/bash

# Docker 单独启动 PostgreSQL 和 MongoDB 命令
# 从项目根目录运行此脚本

echo "======================================"
echo "启动数据库容器"
echo "======================================"

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# 创建 Docker 网络
echo "创建 Docker 网络..."
echo "newhand" | sudo -S docker network create aipaper-network 2>/dev/null || echo "网络已存在"

# 启动 PostgreSQL 14
echo ""
echo "1. 启动 PostgreSQL 14..."
echo "newhand" | sudo -S docker run -d \
  --name postgres-aipaper \
  --network aipaper-network \
  -e POSTGRES_USER=admin \
  -e POSTGRES_PASSWORD=newhand \
  -e POSTGRES_DB=aipaper_db \
  -p 5432:5432 \
  -v postgres-aipaper-data:/var/lib/postgresql/data \
  -v "$SCRIPT_DIR/init-postgres.sql:/docker-entrypoint-initdb.d/init.sql" \
  --restart unless-stopped \
  postgres:14-alpine

# 启动 MongoDB 6.0
echo ""
echo "2. 启动 MongoDB 6.0..."
echo "newhand" | sudo -S docker run -d \
  --name mongodb-aipaper \
  --network aipaper-network \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=newhand \
  -e MONGO_INITDB_DATABASE=aipaper_db \
  -p 27017:27017 \
  -v mongodb-aipaper-data:/data/db \
  -v mongodb-aipaper-config:/data/configdb \
  -v "$SCRIPT_DIR/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js" \
  --restart unless-stopped \
  mongo:6.0

# 等待容器启动
echo ""
echo "等待容器启动..."
sleep 5

# 检查容器状态
echo ""
echo "容器状态："
echo "newhand" | sudo -S docker ps | grep -E "IMAGE|postgres-aipaper|mongodb-aipaper"

echo ""
echo "======================================"
echo "数据库容器启动完成！"
echo "======================================"
echo ""
echo "连接信息："
echo "PostgreSQL:"
echo "  Host: localhost"
echo "  Port: 5432"
echo "  Database: aipaper_db"
echo "  Username: admin"
echo "  Password: newhand"
echo ""
echo "MongoDB:"
echo "  Host: localhost"
echo "  Port: 27017"
echo "  Database: aipaper_db"
echo "  Username: admin"
echo "  Password: newhand"
echo "  连接字符串: mongodb://admin:newhand@localhost:27017/aipaper_db?authSource=admin"
echo ""
echo "======================================"
echo ""
echo "管理命令："
echo "查看日志："
echo "  sudo docker logs postgres-aipaper"
echo "  sudo docker logs mongodb-aipaper"
echo ""
echo "停止容器："
echo "  sudo docker stop postgres-aipaper mongodb-aipaper"
echo ""
echo "启动已存在的容器："
echo "  sudo docker start postgres-aipaper mongodb-aipaper"
echo ""
echo "删除容器："
echo "  sudo docker rm -f postgres-aipaper mongodb-aipaper"
echo ""
echo "删除数据卷（谨慎！会删除所有数据）："
echo "  sudo docker volume rm postgres-aipaper-data mongodb-aipaper-data mongodb-aipaper-config"